import React, { PureComponent } from 'react';
import { Button, Card, Input, Table, Divider, Form, Select, Row, Col, Icon, Popover, PageHeader, DatePicker, TimePicker, message, Spin } from 'antd';
import FooterToolbar from '@/components/FooterToolbar';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { debug } from 'util';
import styles from './style.less';
import request from '@/utils/request';
import { stringify } from 'qs';

const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;
const { TextArea } = Input;

const formItemLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
    },
};

const fieldLabels = {
    name: '仓库名',
    url: '仓库域名',
    owner: '仓库管理员',
    approver: '审批人',
    dateRange: '生效日期',
    type: '仓库类型',
    name2: '任务名',
    url2: '任务描述',
    owner2: '执行人',
    approver2: '责任人',
    dateRange2: '生效日期',
    type2: '任务类型',
};

@Form.create()
export default class MenuDialog extends PureComponent {

    constructor(props) {
        super(props);
        const { query: { isEdit, menuId } } = props.location;

        this.state = {
            isEdit,
            menuId,
            submitting: false,
            formValue: {
                sysId: undefined,
                treeUp: undefined,
                menuId: undefined,
                menuName: undefined,
                menuNamePy: undefined,
                menuUrl: undefined,
                remark: undefined,
                menuIcon: undefined,
            }
        };
    }

    componentDidMount() {
        const { isEdit, menuId, submitting, formValue } = this.state;
        const { getFieldsValue } = this.props.form;
        const { location: { pathname } } = this.props;

        const formSerialKey = "dialog-serial:" + pathname;
        let targetState = formValue;

        if (isEdit === true || isEdit === 'true') {
            this.setState({
                submitting: true
            });
            const params = { menuId };
            request(`/api/sys/menu/queryById?${stringify(params)}`)
                .then((root) => {
                    this.setState({
                        formValue: root.data,
                        submitting: false
                    });
                })

        } else {
            //插入菜单
            if (localStorage) {
                //从 localStorage 中读取暂存的表单
                const value = localStorage.getItem(formSerialKey);
                if (value) {
                    try {
                        targetState = { ...formValue, ...JSON.parse(value) };
                    } catch (e) {
                    }
                }
                this.setState({ formValue: targetState, fh })
            }

            //每隔 2 秒，暂存表单一次
            const fh = setInterval(function () {
                if (localStorage) {
                    localStorage.setItem(formSerialKey, JSON.stringify(getFieldsValue()));
                }
            }, 2000);
        }
    }

    componentWillUnmount() {
        const { fh } = this.state;
        clearInterval(fh);
    }

    validate = () => {
        const { form: { validateFieldsAndScroll }, dispatch, } = this.props;

        validateFieldsAndScroll((error, values) => {
            console.log(values);
            if (!error) {
                this.setState({ submitting: true });
                setTimeout(() => {
                    this.setState({ submitting: false });
                }, 1000);
            }
        });
    }


    getErrorInfo = () => {
        const {
            form: { getFieldsError },
        } = this.props;
        const errors = getFieldsError();
        const errorCount = Object.keys(errors).filter(key => errors[key]).length;
        if (!errors || errorCount === 0) {
            return null;
        }
        const scrollToField = fieldKey => {
            const labelNode = document.querySelector(`label[for="${fieldKey}"]`);
            if (labelNode) {
                labelNode.scrollIntoView(true);
            }
        };
        const errorList = Object.keys(errors).map(key => {
            if (!errors[key]) {
                return null;
            }
            return (
                <li key={key} className={styles.errorListItem} onClick={() => scrollToField(key)}>
                    <Icon type="cross-circle-o" className={styles.errorIcon} />
                    <div className={styles.errorMessage}>{errors[key][0]}</div>
                    <div className={styles.errorField}>{fieldLabels[key]}</div>
                </li>
            );
        });
        return (
            <span className={styles.errorIcon}>
                <Popover
                    title="表单校验信息"
                    content={errorList}
                    overlayClassName={styles.errorPopover}
                    trigger="click"
                    getPopupContainer={trigger => trigger.parentNode}
                >
                    <Icon type="exclamation-circle" />
                </Popover>
                {errorCount}
            </span>
        );
    };

    render() {

        const { isEdit, submitting, formValue } = this.state;
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = null;

        return (
            <PageHeaderWrapper title={isEdit ? '编辑菜单' : '添加菜单'}>
                <Card bordered={false}>
                    <Spin spinning={submitting} delay={50}>
                        <Form layout="vertical">
                            <Row gutter={16}>
                                <Col lg={6} md={12} sm={24}>
                                    <Form.Item label='所属平台' {...formItemLayout}>
                                        {
                                            getFieldDecorator('sysId', {
                                                initialValue: formValue.sysId,
                                                rules: [{ required: true, message: "所属平台必填" }],
                                            })
                                                (<Input />)
                                        }
                                    </Form.Item>
                                </Col>
                                <Col lg={6} md={12} sm={24}>
                                    <Form.Item label='上级菜单' {...formItemLayout}>
                                        {
                                            getFieldDecorator('treeUp', {
                                                initialValue: formValue.treeUp,
                                            })
                                                (<Input />)
                                        }
                                    </Form.Item>
                                </Col>
                            </Row>
                            <Row gutter={16}>
                                <Col lg={6} md={12} sm={24}>
                                    <Form.Item label='菜单名称' {...formItemLayout}>
                                        {
                                            getFieldDecorator('menuName', {
                                                initialValue: formValue.menuName,
                                                rules: [{ required: true, message: "菜单名称必填" }],
                                            })
                                                (<Input />)
                                        }
                                    </Form.Item>
                                </Col>
                                <Col lg={6} md={12} sm={24}>
                                    <Form.Item label='图标' {...formItemLayout}>
                                        {
                                            getFieldDecorator('menuIcon', {
                                                initialValue: formValue.menuIcon,
                                                rules: [],
                                            })(
                                                <Select >
                                                    <Option value="">无</Option>
                                                    <Option value="fa fa-desktop">桌面</Option>
                                                    <Option value="fa fa-file-o">文件</Option>
                                                    <Option value="fa fa-wpforms">日历</Option>
                                                    <Option value="fa fa-th-list">一级菜单</Option>
                                                    <Option value="fa fa-list-ul">二级菜单</Option>
                                                    <Option value="fa fa-bars">列表</Option>
                                                    <Option value="fa fa-search">搜索</Option>
                                                    <Option value="fa fa-database">数据库</Option>
                                                    <Option value="fa fa-history">历史</Option>
                                                    <Option value="fa fa-globe">地球</Option>
                                                    <Option value="fa fa-flag">旗帜</Option>
                                                    <Option value="fa fa-filter">漏斗</Option>
                                                    <Option value="fa fa-envelope">信封</Option>
                                                    <Option value="fa fa-diamond">钻石</Option>
                                                    <Option value="fa fa-cubes">立方体</Option>
                                                    <Option value="fa fa-coffee">咖啡</Option>
                                                    <Option value="fa fa-cogs">齿轮组</Option>
                                                    <Option value="fa fa-cog">齿轮</Option>
                                                    <Option value="fa fa-cart-plus">购物车</Option>
                                                    <Option value="fa fa-bell">铃铛</Option>
                                                    <Option value="fa fa-barcode">长形码</Option>
                                                    <Option value="fa fa-university">大学</Option>
                                                    <Option value="fa fa-balance-scale">天秤</Option>
                                                    <Option value="fa fa-asterisk">雪花</Option>
                                                    <Option value="fa fa-podcast">广播</Option>
                                                    <Option value="fa fa-truck">卡车</Option>
                                                    <Option value="fa fa-shopping-basket">购物栏</Option>
                                                    <Option value="fa fa-plug">插头</Option>
                                                    <Option value="fa fa-pie-chart">饼图</Option>
                                                    <Option value="fa fa-magnet">磁铁</Option>
                                                    <Option value="fa fa-user-circle">用户</Option>
                                                    <Option value="fa fa-users">用户组</Option>
                                                </Select>)
                                        }
                                    </Form.Item>
                                </Col>
                            </Row>
                            <Row gutter={16}>
                                <Col lg={24} md={24} sm={24}>
                                    <Form.Item label='功能URL' {...formItemLayout}>
                                        {
                                            getFieldDecorator('menuUrl', {
                                                initialValue: formValue.menuUrl,
                                            })
                                                (<Input />)
                                        }
                                    </Form.Item>
                                </Col>
                            </Row>
                            <Row gutter={16}>
                                <Col lg={24} md={24} sm={24}>
                                    <Form.Item label='备注' {...formItemLayout}>
                                        {
                                            getFieldDecorator('remark', {
                                                initialValue: formValue.remark,
                                            })
                                                (<TextArea rows={4} />)
                                        }
                                    </Form.Item>
                                </Col>
                            </Row>
                        </Form>
                    </Spin>
                </Card>

                <FooterToolbar style={{ width: '100%', }}>
                    {this.getErrorInfo()}
                    <Button type="primary" onClick={this.validate} loading={submitting}>提交</Button>
                </FooterToolbar>
            </PageHeaderWrapper>
        )
    }
}
